package com.hzqy.web.ac.epg;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hzqy.commons.utils.FileType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.hzqy.commons.utils.ConvertBeanUtil;
import com.hzqy.commons.utils.ExcelUtil;
import com.hzqy.commons.utils.ExcelUtil.MyEntry;
import com.hzqy.service.epg.AcUserBillServiceBean;
import com.hzqy.service.epg.AcProductService;
import com.hzqy.service.system.SysVoProcessServiceBeen;
import com.hzqy.web.vo.SysProductVo;
import com.hzqy.web.vo.epg.AcPopupsListVo;
import com.hzqy.web.vo.epg.AcUserBillVo;
import com.hzqy.web.vo.epg.ActivityProductVo;

@Controller
@RequestMapping("/")
public class UserBillAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	private static final String[] allowedFileType = new String[]{"png", "jpg", "gif","zip","jar","tar","docx","doc","xlsx","xls","flv","mp4","mp3","mpg","avi","mov","wmv"};
	@Resource
	private AcUserBillServiceBean acUserBillServiceBean;
	@Resource
	private SysVoProcessServiceBeen voProcessServiceBean;
	@Resource
	private AcProductService acProductService;
	/**
	 * @param aub
	 * @return
	 */
	@RequestMapping(value="/ac/bill_list")
	@ResponseBody
	public Object billList(AcUserBillVo aub,String ordertime,String endtime, int page, int rows,String repeat) {
		Map<String,Object> map = new HashMap<String,Object>();
		if (ordertime!=null && ordertime!="") {
			aub.setF_aub_ordertime(ordertime);
		}
		if (endtime!=null && endtime!="") {
			aub.setF_aub_endtime(endtime);
		}
		map = acUserBillServiceBean.selectUserBillList(aub,page,rows,repeat);
		return map;
	}
	@RequestMapping(value="/ac/bill_excel_list")
	@ResponseBody
	public void billExcelList(AcUserBillVo aub,String ordertime,String endtime,String repeat,HttpServletResponse response)throws IOException {
		Map<String,Object> ExcelListMap = new HashMap<String, Object>();
		if (ordertime!=null&&ordertime!="") {
			aub.setF_aub_ordertime(ordertime);
		}
		if (endtime!=null && endtime!="") {
			aub.setF_aub_endtime(endtime);
		}
		ExcelListMap =  acUserBillServiceBean.selectUserBillExcelList(aub,repeat);
		List<AcUserBillVo> list=new ArrayList<AcUserBillVo>();
		list = (List<AcUserBillVo>)ExcelListMap.get("rows");
		voProcessServiceBean.voProcess(list);
		List<MyEntry<String, String>> excelCpHeader=new ArrayList<MyEntry<String, String>>();
		excelCpHeader.add(new MyEntry<String,String>("f_aub_serverid","业务账号"));
		excelCpHeader.add(new MyEntry<String,String>("f_aub_productid","活动ID"));
		excelCpHeader.add(new MyEntry<String,String>("f_aub_productcode","产品ID"));
		excelCpHeader.add(new MyEntry<String,String>("f_aub_ordertime","订购时间"));
		excelCpHeader.add(new MyEntry<String,String>("f_aub_endtime","到期时间"));
		excelCpHeader.add(new MyEntry<String,String>("f_aub_type","用户状态"));
		boolean flag=ExcelUtil.generateExcel(list, excelCpHeader, response);
	}

	/**
	 * 批量导入
	 * @param file	excel文件
	 * @param response
	 * @return
	 */
/*	@RequestMapping("/ac/excelUserBill")
	@ResponseBody
	public Object insertUserBill(@RequestParam(value = "uploadify") MultipartFile file , 
			 HttpServletResponse response,HttpServletRequest request) throws Exception {
		response.setContentType("text/html;charset=UTF-8");

		if (FileType.checkFileType(file.getInputStream(), allowedFileType)) {
			int success = 0;
			int repeat = 0;
			int fapid = Integer.valueOf(request.getParameter("fapid"));
			JSONArray emptyArr = new JSONArray();
			StringBuffer str = new StringBuffer();
			ActivityProductVo acList = acProductService.selctActivity(fapid);//查询活动配置
			List<SysProductVo> productList = acUserBillServiceBean.productDetailed();//查询产品配置表
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
			InputStream is = null;
			try {
				LOG.debug("批量导入活动开始");
				is = file.getInputStream();
				List<Map<String, Object>> list = ExcelUtil.parseExcel(is, ExcelUtil.ALLOWED_EMPTY_MODE, new String[]{"ITV账号", "产品ID"});
				LOG.debug("解析excel完成, 开始循环入库");
				for (int i = 0; i < list.size(); i++) {// 检查产品表中是否配置产品
					boolean b1 = true;//判断该产品是否配置
					try {
						Map<String, Object> m = list.get(i);
						String pro = m.get("产品ID").toString();
						for (int j = 0; j < productList.size(); j++) {
							String f_sp_productcode = productList.get(j).getF_sp_productcode();
							if (pro.equals(f_sp_productcode)) {
								b1 = false;
								break;
							}
						}
						if (b1) {//没有配置，直接返回配置，不执行插入，避免数据重复
							str.append("批量导入失败.请到产品管理配置产品： " + m.get("产品ID"));
							LOG.debug("批量导入失败.请到产品管理配置产品： " + m.get("产品ID"));
							return str.toString();
						}
					} catch (Exception e) {
						//str.append("批量导入失败: " + e.getMessage());
						//LOG.debug("批量导入失败: " + e.getMessage()); return str.toString();
					}
				}


				for (int i = 0; i < list.size(); i++) {
					try {
						Map<String, Object> m = list.get(i);
						AcUserBillVo userBill = ConvertBeanUtil.getBeanFromMap(m, AcUserBillVo.class, AcUserBillVo.class.getName());
						userBill.setF_aub_type(1);//默认导入用户
						userBill.setF_aub_productid(fapid);
						String startTime = String.valueOf(m.get("订购时间"));
						if ("".equals(startTime) || "null".equals(startTime)) {
							startTime = "2018-01-01 00:00:00";
						} else {
							if (startTime.indexOf("-") != -1) {
								startTime = sdf.format(sdf1.parse(startTime));
							} else if (startTime.indexOf("/") != -1) {
								startTime = sdf.format(sdf2.parse(startTime));
							} else {
								if (startTime.matches("^[0-9]*$")) {
									Calendar calendar = new GregorianCalendar(1900, 0, -1);
									calendar.add(Calendar.DATE, Integer.valueOf(startTime));
									startTime = sdf.format(calendar.getTime());
								} else {
									startTime = "2017-10-10 00:00:00";
								}
							}
						}
						String ordertime = startTime;
						startTime = startTime.substring(0, 10);
						userBill.setF_aub_ordertime(startTime);
						boolean insert = false;
						//判断该用户订购的产品是否在活动产品包中
						if (acList.getF_ap_productcode().indexOf(String.valueOf(userBill.getF_aub_productcode())) != -1) {
							insert = true;
						}
						*//*
						 * for (int j = 0; j < acList.size(); j++) {
						 * if(acList.get(j).getF_ap_productcode().indexOf(String.valueOf(userBill.
						 * getF_aub_productcode()))!=-1) {
						 * userBill.setF_aub_productid(acList.get(j).getF_ap_id()); insert = true;
						 * break; } }
						 *//*
						if (insert) {
							String endTime = String.valueOf(m.get("到期时间"));
							String productName = String.valueOf(m.get("产品包名称"));
							SysProductVo sysProductVo = null;
							boolean productflag = false;
							if ("".equals(endTime) || "null".equals(endTime)) {
								for (int j = 0; j < productList.size(); j++) {//找到该用户订购产品对应产品配置
									if (productList.get(j).getF_sp_productcode().equals(String.valueOf(userBill.getF_aub_productcode()))) {
										sysProductVo = productList.get(j);
										endTime = getEndtime(sysProductVo, startTime);//设置到期时间
										userBill.setF_aub_endtime(endTime);
										productflag = true;
										break;
									}
								}
							} else {// 根据表格中数据
								if (endTime.indexOf("-") != -1) {
									endTime = sdf.format(sdf1.parse(endTime));
								} else if (endTime.indexOf("/") != -1) {
									endTime = sdf.format(sdf2.parse(endTime));
								} else {
									if (endTime.matches("^[0-9]*$")) {
										Calendar calendar = new GregorianCalendar(1900, 0, -1);
										calendar.add(Calendar.DATE, Integer.valueOf(endTime));
										endTime = sdf.format(calendar.getTime());
									} else {
										endTime = "2018-10-10 00:00:00";
									}
								}
								userBill.setF_aub_endtime(endTime);
								productflag = true;
							}
							//设置订购产品名称
							if ("".equals(productName) || "null".equals(productName)) {
								if (sysProductVo == null) {
									for (int j = 0; j < productList.size(); j++) {//找到该用户订购产品对应产品配置
										if (productList.get(j).getF_sp_productcode().equals(String.valueOf(userBill.getF_aub_productcode()))) {
											sysProductVo = productList.get(j);
											endTime = getEndtime(sysProductVo, startTime);//设置到期时间
											userBill.setF_aub_productname(sysProductVo.getF_sp_name());
											break;
										}
									}
								} else {
									userBill.setF_aub_productname(sysProductVo.getF_sp_name());
								}
							} else {
								userBill.setF_aub_productname(productName);
							}
							if (!productflag) {
								LOG.debug("请在产品管理中检查是否配置产品包 ：" + userBill.getF_aub_productcode());
								str.append("第").append(i + 1).append("条 出错!请到检查产品： " + userBill.getF_aub_productcode()).append("<br/>");
							} else {
								int count = acUserBillServiceBean.selectUserBillCountByUser(userBill);
								if (count == 0) {//不存在
									userBill.setF_aub_ordertime(ordertime);
									int flag = acUserBillServiceBean.insertUserBillExcel(userBill, emptyArr.toJSONString());
									success += (flag > 0 ? 1 : 0);
								} else if (count > 1) {//多条记录，删除多余记录
									acUserBillServiceBean.deleteUserBill(userBill);
								} else {
									repeat = repeat + 1;
								}
							}
						} else {
							str.append("第").append(i + 1).append("条 出错!没有资格").append("<br/>");
						}
					} catch (Exception e) {
						//str.append("第").append(i+1).append("条 出错! ").append(e.getMessage()).append("<br/>");
					}
				}
				LOG.debug("批量完成");
				LOG.debug("批量导入完成， 一共：" + list.size() + "条数据, 成功" + success + ", 重复" + repeat + ", 失败" + (list.size() - success - repeat));
				str.append("批量导入完成， 一共：").append(list.size()).append("条数据, 成功").append(success).append(", 重复").append(repeat).append(",失败").append(list.size() - success - repeat);
			} catch (Exception e) {
				LOG.debug("异常：：：：：", e);
				str.append("批量导入失败: ");
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
			return str.toString();
		} else {
			return "";
		}
	}*/
	
	public String getEndtime(SysProductVo sysProductVo,String startTime) {
		int scenes = sysProductVo.getF_sp_scenes();//1线上，2线下 ，线上多加一个月
		int f_sp_type = sysProductVo.getF_sp_type();//1 为包月，7为半年，4为双包月，5为包年，6为包季度
		int month = 1;
		if(f_sp_type==5) {
			if(scenes==2) {
				month = 12;
			}else {
				month = 13;
			}
		}else if(f_sp_type==6) {
			if(scenes==2) {
				month = 3;
			}else {
				month = 4;
			}
		}else if (f_sp_type==1) {
			if(scenes==1) {
				month = 2;
			}
		}else if(f_sp_type==7) {
			if(scenes==2) {
				month = 6;
			}else {
				month = 7;
			}
		}else if(f_sp_type==4) {
			
			month = 2;
			
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		//开始时间去闰月 采用加1天  3.1号开始算
		if(startTime.indexOf("02-29")!=-1) {
			try {
				startTime = sdf.format(new Date(sdf.parse(startTime).getTime() + 24 * 3600 * 1000));
			}catch(Exception ex) {
				LOG.error("闰月增加时间失败!!!");
			}
		}
		//计算订购到期时间
		String endTime = "";
		try {
			Date dt = sdf.parse(startTime);  
			Calendar rightNow = Calendar.getInstance();  
			rightNow.setTime(dt);  
			rightNow.add(Calendar.MONTH, month);  
			Date dt1 = rightNow.getTime();  
			endTime = sdf1.format(dt1); 
		}catch(Exception ex) {
			LOG.error("计算订购到期时间失败!!!");
		}
		return endTime;
	}
	/**
	 * 用户弹窗查看
	 * @param f_apul_activityid  活动id
	 * @param f_apul_serverid  用户账号
	 * @param starttime  查询条件，开始时间
	 * @param endtime    查询条件，结束时间
	 * @param page
	 * @param rows
	 * @param repeat    弹窗次数
	 * @return
	 */
	@RequestMapping(value="/ac/acPopulist")
	@ResponseBody
	public Object acPopulist(int f_apul_activityid,String f_apul_serverid,String starttime,String endtime,int page, int rows,int repeat) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(f_apul_serverid!=null && f_apul_serverid!="") {
			map.put("f_apul_serverid", f_apul_serverid);
		}
		if(starttime!=null && starttime!="") {
			map.put("starttime", starttime);
		}
		if(endtime!=null && endtime!="") {
			map.put("endtime", endtime);
		}
		if(repeat!=0) {
			map.put("repeat", repeat);
		}
		if(f_apul_activityid!=0) {
			map.put("f_apul_activityid", f_apul_activityid);
		}
		map = acUserBillServiceBean.selectAcPopupsList(map,page,rows);
		return map;
	}
	/**
	 * 用户弹框导出
	 * @param f_apul_serverid 用户账号
	 * @param f_apul_activityid 活动id
	 * @param ordertime 开始时间
	 * @param endtime 结束时间
	 * @param repeat
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/ac/pop_excel_list")
	@ResponseBody
	public void popExcelList(int f_apul_activityid,String f_apul_serverid,String starttime,String endtime,int repeat,HttpServletResponse response)throws IOException {
		Map<String,Object> map = new HashMap<String,Object>();
		if(f_apul_serverid!=null && f_apul_serverid!="") {
			map.put("f_apul_serverid", f_apul_serverid);
		}
		if(starttime!=null && starttime!="") {
			map.put("starttime", starttime);
		}
		if(endtime!=null && endtime!="") {
			map.put("endtime", endtime);
		}
		if(repeat!=0) {
			map.put("repeat", repeat);
		}
		if(f_apul_activityid!=0) {
			map.put("f_apul_activityid", f_apul_activityid);
		}
		map = acUserBillServiceBean.selectAcPopupsList(map,1,99999);
		List<AcPopupsListVo> list=new ArrayList<AcPopupsListVo>();
		list = (List<AcPopupsListVo>)map.get("rows");
		voProcessServiceBean.voProcess(list);
		List<MyEntry<String, String>> excelCpHeader=new ArrayList<MyEntry<String, String>>();
		excelCpHeader.add(new MyEntry<String,String>("f_apul_serverid","业务账号"));
		excelCpHeader.add(new MyEntry<String,String>("f_apul_cdate","弹窗时间"));
		boolean flag=ExcelUtil.generateExcel(list, excelCpHeader, response);
	}
	
}
